/*
 * Programmer	:	Muhammad Mohsin Mughal
 * Project	 	:  	Travel Experts Phase 3 (Assign Customer to Active Agent)
 * Language  	:  	Java
 * Date Written	:   March 20, 2011.
 * Student Id	:	559933	
 */

import java.awt.BorderLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Vector;

import javax.swing.ComboBoxModel;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListModel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;

/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class CustomerAgtDialog extends javax.swing.JDialog {
	// Class level Definition
	private Connection conn;
	private JLabel jLabel2;
	private JLabel jLabel1;
	private Statement stmt;
	private ResultSet rs;
	private ResultSet rs1;
	private String agtId;
	private String agtStatus;
	private JTable agtTable;
	private JPanel jPanel1;
	private JScrollPane jScrollPane1;
	private JScrollPane jScrollPane2;
	private JLabel lblCustTable;
	private JLabel lblAgentTable;
	private JTable CustTable;
	DefaultTableModel tblAgentsModel = new DefaultTableModel();
	TableModel CustTableModel = 
		new DefaultTableModel(
				);
	String updateAgtid;
	String updateCustid;
	private JButton btnUpdateAll;
	private JComboBox cbAgent;
	private JButton btnCancel;
	private JButton txtUpdate;
	private JTextField txtCustId;
	private JTextField txtAgentId;
	/**
	* Auto-generated main method to display this JDialog
	*/
	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				JFrame frame = new JFrame();
				CustomerAgtDialog inst = new CustomerAgtDialog(frame);
				inst.setVisible(true);
			}
		});
	}
	
	public CustomerAgtDialog(JFrame frame) {
		super(frame);
		initGUI();
		try
		{
			loadtable();
		} 
		catch (SQLException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	// Constructor to receive the selected agent id from Main frame
	
	public CustomerAgtDialog(JPanel panel, String agtId) {
		
		//super(frame);
		
		this.agtId=agtId;   // you cant use directly 
		initGUI();
		
		
		
		try
		{
		//	Creating the Agent and Customer Tables
			loadtable();
			loadtable1();
		} 
		catch (SQLException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	// Creating the GUI
	
	private void initGUI() {
		try {
			setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
			getContentPane().setLayout(null);
		
				
				this.setTitle("Customer And Agent");
				{
					jPanel1 = new JPanel();
					getContentPane().add(jPanel1);
					jPanel1.setBounds(0, 0, 784, 545);
					jPanel1.setLayout(null);
					{
						jScrollPane1 = new JScrollPane();
						jPanel1.add(jScrollPane1);
						jPanel1.add(getJScrollPane2());
						jPanel1.add(getLblCustTable());
						jPanel1.add(getLblAgentTable());
						jPanel1.add(getTxtAgentId());
						jPanel1.add(getTxtCustId());
						jPanel1.add(getTxtUpdate());
						jPanel1.add(getBtnCancel());
						jPanel1.add(getCbAgent());
						jPanel1.add(getBtnUpdateAll());
						jPanel1.add(getBtnUpdateAll());
						jScrollPane1.setBounds(12, 33, 253, 282);
						{
							// Define Agent Table to show the All the Active Agents
							
							agtTable = new JTable();
							jScrollPane1.setViewportView(agtTable);
							agtTable.setModel(tblAgentsModel);
							agtTable.setBounds(25, 46, 597, 87);
							tblAgentsModel.setColumnCount(4);
							agtTable.addKeyListener(new KeyListener() {
								
								@Override
								public void keyTyped(KeyEvent e) {
									// TODO Auto-generated method stub
									
								}
								
								@Override
								public void keyReleased(KeyEvent e) {
									// TODO Auto-generated method stub
									
								}
								
								@Override
								public void keyPressed(KeyEvent e) {
									// TODO Auto-generated method stub
									if(e.getKeyCode()==e.VK_DOWN)
									{
										if(agtTable.getRowCount()>agtTable.getSelectedRow()+1)
										{
											try {
												populateForm(agtTable.getSelectedRow()+1);
											} catch (ParseException e1) {
												// TODO Auto-generated catch block
												e1.printStackTrace();
											}
										}
									}
									else if(e.getKeyCode()==e.VK_UP) 
									{
										if(agtTable.getSelectedRow()==0)
										{
											return;
										}
										if(agtTable.getSelectedRow() <= agtTable.getRowCount()-1)
										{
											try {
												populateForm(agtTable.getSelectedRow()-1);
											} catch (ParseException e1) {
												// TODO Auto-generated catch block
												e1.printStackTrace();
											}
										}
										
									}
									
								}
							});
							
							// Mouse Click Event to Select any Agent
							
							agtTable.addMouseListener(new MouseAdapter() {
								public void mouseClicked(MouseEvent e) 
								{
									// TODO Auto-generated method stub
									super.mouseClicked(e);
									try {
										populateForm(agtTable.getSelectedRow());
									
										
									} catch (ParseException e1) {
										// TODO Auto-generated catch block
										e1.printStackTrace();
									}
								}
							});
			}
			this.setBounds(300, 300,768, 421);
			//this.setSize(768, 421);
					}}}
				catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	// function the connect to the Oracle database
	
	private void databaseConnection()
	{
		try 
		{
			Class.forName("oracle.jdbc.driver.OracleDriver");
			conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl", "ictoosd", "ictoosd");
			stmt = conn.createStatement();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	// filling the Active Agents data in the Agent table
	
	public void loadtable() throws SQLException
	{
		while (agtTable.getRowCount() > 0)
		 {
			  ((DefaultTableModel)agtTable.getModel()).removeRow(0);
		 }
		databaseConnection();
		agtStatus = "Active";
		System.out.println("Before query Agt Id:" +agtId);
		rs = stmt.executeQuery("select AGENTID,AGTFIRSTNAME,AGTMIDDLEINITIAL,AGTLASTNAME from Agents where AGENTSTATUS =" + "'Active'" + " and AGENTID <>" +agtId);
		System.out.println("Agt Id:" +agtId);
		System.out.println(agtStatus);
				
		ResultSetMetaData rsmd = rs.getMetaData();
		String [] header=new String[rsmd.getColumnCount()];
		for(int j=1;j<=rsmd.getColumnCount();j++)
		{
			header[j-1]=rsmd.getColumnLabel(j);
		}
		while(rs.next())
		{
			
			
			Object [] myAgt = { rs.getInt(1),rs.getString(2),rs.getString(3),rs.getString(4)};
					
					
			
			tblAgentsModel.addRow(myAgt);
		}
		Enumeration<TableColumn> cols = agtTable.getColumnModel().getColumns();
		int i=0;
		while (cols.hasMoreElements())
		{
			TableColumn col = cols.nextElement();
			col.setHeaderValue(header[i++]);
		}
		conn.close();
		
	
	}
	
	// fill the data of all customers attached to the selected Inactive agent in the 
	// Customer Table
	
	public void loadtable1() throws SQLException
	{
		while (CustTable.getRowCount() > 0)
		 {
			  ((DefaultTableModel)CustTable.getModel()).removeRow(0);
		 }
		databaseConnection();	
		
		agtStatus = "Active";
		rs1 = stmt.executeQuery("select * from CUSTOMERS where AGENTID =" + agtId );
		System.out.println(agtId);
		System.out.println(agtStatus);
		ResultSetMetaData rsmd = rs1.getMetaData();
		String [] header=new String[rsmd.getColumnCount()];
		for(int j=1;j<=rsmd.getColumnCount();j++)
		{
			header[j-1]=rsmd.getColumnLabel(j);
		}
	
		
		while(rs1.next())
		{
			
			/*Customers cust = new Customers();
			cust.setcustomerId(rs1.getInt(1));
			cust.setcustFirstName(rs1.getString(2));
			cust.setcustLastName(rs1.getString(3));
			cust.setcustAddress(rs1.getString(4));
			cust.setcustCity(rs1.getString(5));
			cust.setcustProv(rs1.getString(6));
			cust.setcustPostal(rs1.getString(7));
			cust.setcustCountry(rs1.getString(8));
			cust.setcustBusPhone(rs1.getString(9));
			cust.setcustHomePhone(rs1.getString(10));
			cust.setcustEmail(rs1.getString(11));
			cust.setagentId(rs1.getInt(12));
			list1.add(cust);*/
			
			Object [] myCust = { rs1.getInt(1),rs1.getString(2),rs1.getString(3)};
			((DefaultTableModel) CustTableModel).addRow(myCust);
		}
		Enumeration<TableColumn> cols = CustTable.getColumnModel().getColumns();
		int i=0;
		while (cols.hasMoreElements())
		{
			TableColumn col = cols.nextElement();
			col.setHeaderValue(header[i++]);
		}
	//	disableFields();
		conn.close();
	}
	
	// call this function to go to quit the program
	
	private void doSave()
	{
		this.dispose();
	}
	

	private JLabel getJLabel1() {
		if(jLabel1 == null) {
			jLabel1 = new JLabel();
			jLabel1.setText("Available Active Agents to Select");
			jLabel1.setBounds(5, 0, 308, 14);
			jLabel1.setFont(new java.awt.Font("Abyssinica SIL",1,16));
		}
		return jLabel1;
	}
	
	private JLabel getJLabel2() {
		if(jLabel2 == null) {
			jLabel2 = new JLabel();
			jLabel2.setText("Customers Of InActive Agent");
			jLabel2.setBounds(461, 0, 301, 14);
			jLabel2.setFont(new java.awt.Font("Abyssinica SIL",1,16));
		}
		return jLabel2;
	}
	private void populateForm(int row) throws ParseException 
	{
		
		
		
		// TODO Auto-generated method stub
		
		String [] fields=new String[agtTable.getColumnCount()];
		
		for(int i=0;i<agtTable.getColumnCount();i++)
		{
			fields[i]=""+tblAgentsModel.getValueAt(agtTable.getSelectedRow(), i);
		}
		
				txtAgentId.setText(fields[0]);
					
		}
	
	private void populateForm1(int row) throws ParseException 
	{
		
		
		
		// TODO Auto-generated method stub
		
		String [] fields=new String[CustTable.getColumnCount()];
		
		for(int i=0;i<CustTable.getColumnCount();i++)
		{
			fields[i]=""+CustTableModel.getValueAt(CustTable.getSelectedRow(), i);
		}
		txtCustId.setText(fields[0]);
		}
	
	private JTable getCustTable() {
		if(CustTable == null) {
			
			CustTable = new JTable();
			CustTable.setModel(CustTableModel);
			((DefaultTableModel) CustTableModel).setColumnCount(3);
			CustTable.setBounds(465, 22, 265, 212);
			CustTable.addKeyListener(new KeyListener() {
				
				@Override
				public void keyTyped(KeyEvent e) {
					// TODO Auto-generated method stub
					
				}
				
				@Override
				public void keyReleased(KeyEvent e) {
					// TODO Auto-generated method stub
					
				}
				
				@Override
				public void keyPressed(KeyEvent e) {
					// TODO Auto-generated method stub
					if(e.getKeyCode()==e.VK_DOWN)
					{
						if(CustTable.getRowCount()>CustTable.getSelectedRow()+1)
						{
							try {
								populateForm1(CustTable.getSelectedRow()+1);
							} catch (ParseException e1) {
								// TODO Auto-generated catch block
								e1.printStackTrace();
							}
						}
					}
					else if(e.getKeyCode()==e.VK_UP) 
					{
						if(CustTable.getSelectedRow()==0)
						{
							return;
						}
						if(CustTable.getSelectedRow() <= CustTable.getRowCount()-1)
						{
							try {
								populateForm1(CustTable.getSelectedRow()-1);
							} catch (ParseException e1) {
								// TODO Auto-generated catch block
								e1.printStackTrace();
							}
						}
						
					}
					
				}
			});
			CustTable.addMouseListener(new MouseAdapter() {
				public void mouseClicked(MouseEvent e) 
				{
					// TODO Auto-generated method stub
					super.mouseClicked(e);
					try {
						populateForm1(CustTable.getSelectedRow());
					
						
					} catch (ParseException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				}
			});
			
		}
		return CustTable;
	}
	
	private JScrollPane getJScrollPane2() {
		if(jScrollPane2 == null) {
			jScrollPane2 = new JScrollPane();
			jScrollPane2.setBounds(466, 33, 265, 277);
			jScrollPane2.setViewportView(getCustTable());
		}
		return jScrollPane2;
	}
	
	private JLabel getLblAgentTable() {
		if(lblAgentTable == null) {
			lblAgentTable = new JLabel();
			lblAgentTable.setText("Table of Active Agents");
			lblAgentTable.setBounds(12, 8, 241, 14);
			lblAgentTable.setFont(new java.awt.Font("Abyssinica SIL",1,12));
		}
		return lblAgentTable;
	}
	
	private JLabel getLblCustTable() {
		if(lblCustTable == null) {
			lblCustTable = new JLabel();
			lblCustTable.setText("Customers Attached to Inactive Agent");
			lblCustTable.setBounds(466, 8, 265, 14);
			lblCustTable.setFont(new java.awt.Font("Abyssinica SIL",1,12));
		}
		return lblCustTable;
	}
	
	private JTextField getTxtAgentId() {
		if(txtAgentId == null) {
			txtAgentId = new JTextField();
			txtAgentId.setBounds(38, 339, 33, 21);
			txtAgentId.setVisible(false);
		}
		return txtAgentId;
	}
	
	private JTextField getTxtCustId() {
		if(txtCustId == null) {
			txtCustId = new JTextField();
			txtCustId.setBounds(556, 339, 37, 21);
			txtCustId.setVisible(false);
		}
		return txtCustId;
	}
	
	private JButton getTxtUpdate() {
		if(txtUpdate == null) {
			txtUpdate = new JButton();
			txtUpdate.setText("Update");
			txtUpdate.setBounds(376, 345, 115, 31);
			txtUpdate.addMouseListener(new MouseAdapter() {
				public void mouseClicked(MouseEvent evt) {
					System.out.println("txtUpdate.mouseClicked, event="+evt);
					//TODO add your code for txtUpdate.mouseClicked
					if(agtTable.getSelectedRow()==-1)
					{
						JOptionPane.showMessageDialog(CustomerAgtDialog.this, "Select an Agent first");
					}
					else if(CustTable.getSelectedRow()==-1)
					{
						JOptionPane.showMessageDialog(CustomerAgtDialog.this, "Select a Customer to add");
					}
					else
					{
						//String UpdateSql = "update CUSTOMERS set AGENTID = '"+CustTable.getValueAt(agtTable.getSelectedRow(),0)+"' " + " where AGENTID = '"+CustTable.getValueAt(CustTable.getSelectedRow(),0)+'"";
						String UpdateSql = "update CUSTOMERS set AGENTID = "+txtAgentId.getText()+" where CUSTOMERID =" + txtCustId.getText();
						System.out.println(UpdateSql);
						try
						{
							databaseConnection();
							System.out.println("before execute");
							stmt.executeUpdate(UpdateSql);
							System.out.println("after execute");
							loadtable();
							loadtable1();
							txtAgentId.setText("");
							txtCustId.setText("");
						} 
						catch (SQLException e)
						{
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
															
					}
					
					
					
				}
			});
		}
		return txtUpdate;
	}
	
	private JButton getBtnCancel() {
		if(btnCancel == null) {
			btnCancel = new JButton();
			btnCancel.setText("Return to Main");
			btnCancel.setBounds(519, 344, 118, 33);
			btnCancel.addMouseListener(new MouseAdapter() {
				public void mouseClicked(MouseEvent evt) {
					System.out.println("btnCancel.mouseClicked, event="+evt);
					//TODO add your code for btnCancel.mouseClicked
					doSave();
				}
			});
		}
		return btnCancel;
	}
	
	private JComboBox getCbAgent() {
		if(cbAgent == null) {
			ComboBoxModel cbAgentModel = 
				new DefaultComboBoxModel(getAgentIDs());
						
			cbAgent = new JComboBox();
			cbAgent.setModel(cbAgentModel);
			cbAgent.setBounds(297, 39, 106, 21);
			
		
		}
		return cbAgent;
	}
	private Vector getAgentIDs() {
		// TODO Auto-generated method stub
		databaseConnection();
		
		Vector<String> agents = new Vector<String>();
		agents.add("Select Any Item");
		try {
			rs = stmt.executeQuery("select agentid from Agents");
			while (rs.next())
			{
				agents.add(rs.getString("agentid"));
			}
			rs.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return agents;
	}
	
	private JButton getBtnUpdateAll() {
		if(btnUpdateAll == null) {
			btnUpdateAll = new JButton();
			btnUpdateAll.setText("Update All");
			btnUpdateAll.setBounds(243, 345, 109, 30);
			btnUpdateAll.addMouseListener(new MouseAdapter() {
				public void mouseClicked(MouseEvent evt) {
					System.out.println("btnUpdateAll.mouseClicked, event="+evt);
					//TODO add your code for btnUpdateAll.mouseClicked
					if(cbAgent.getSelectedItem().equals("Select Any Item"))
					{
						JOptionPane.showMessageDialog(CustomerAgtDialog.this, "Select an AgentId from Combo Box first");
					}
					
					else
					{
						
						//String UpdateSql = "update CUSTOMERS set AGENTID = '"+CustTable.getValueAt(agtTable.getSelectedRow(),0)+"' " + " where AGENTID = '"+CustTable.getValueAt(CustTable.getSelectedRow(),0)+'"";
						String UpdateAllSql = "update CUSTOMERS set AGENTID = "+cbAgent.getSelectedItem()+" where AGENTID =" + agtId;
						System.out.println(UpdateAllSql);
						try
						{
							databaseConnection();
							System.out.println("before execute");
							stmt.executeUpdate(UpdateAllSql);
							System.out.println("after execute");
							loadtable();
							loadtable1();
							ComboBoxModel cbAgentModel = 
								new DefaultComboBoxModel(getAgentIDs());
							cbAgent.setModel(cbAgentModel);
							txtAgentId.setText("");
							txtCustId.setText("");
						} 
						catch (SQLException e)
						{
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
															
					}
					
					
					
				}
			});
		}
		return btnUpdateAll;
	}

}
